package pool

import "chainmaker.org/chainmaker/smarteditor/logger"

type SystemResourcePool struct {
	id       int
	poolSize int
	pool     chan int
}

var log = logger.Get()

//NewSystemResourcePool a resource pool
func NewSystemResourcePool(poolSize int) *SystemResourcePool {
	r := &SystemResourcePool{
		id:       0,
		poolSize: poolSize,
		pool:     make(chan int, poolSize),
	}
	for i := 0; i < poolSize; i++ {
		r.Put()
	}
	return r
}

//Put put an item to pool
func (rp *SystemResourcePool) Put() {
	if len(rp.pool) == rp.poolSize {
		log.Warnf("put item to pool, reach pool max size limit")
		return
	}
	rp.pool <- rp.id
	rp.id = rp.id + 1
}

//Get fetch an item from pool
func (rp *SystemResourcePool) Get() bool {
	if len(rp.pool) == 0 {
		log.Warnf("get item from pool, pool is nil")
		return false
	}
	<-rp.pool
	return true
}
